package personal.emailsender.client;


import java.util.Arrays;

import personal.emailsender.shared.data.EmailContent;
import personal.emailsender.shared.data.ServerResponse;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class MySimpleEmailSender implements EntryPoint {

	private static final String SERVER_ERROR = "An error occurred in server, try again later";

	private final MailSendingDispachingServiceAsync mailSendingService = GWT
			.create(MailSendingDispachingService.class);

	private TextBox buildTextBox(String text) {
		final TextBox fieldBox = new TextBox();
		fieldBox.setText(text);
		return fieldBox;
	}

	/**
	 * This is the entry point method.
	 */
	@Override
	public void onModuleLoad() {
		final Button sendButton = new Button("Send Email");
		// final TextBox nameField = new TextBox();
		// nameField.setText("GWT User");
		final Label errorLabel = new Label();

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		// RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("sendButtonContainer").add(sendButton);

		final TextBox fromEmail = buildTextBox("");
		RootPanel.get("fromEmail").add(fromEmail);
		final TextBox toEmails = buildTextBox("");
		RootPanel.get("toEmails").add(toEmails);
		final TextBox subject = buildTextBox("");
		RootPanel.get("subject").add(subject);
		final RichTextArea content = new RichTextArea();
		// final TextBox content = buildTextBox("Email Content");
		RootPanel.get("content").add(content);
		RootPanel.get("errorLabelContainer").add(errorLabel);

		// start from "from" field
		fromEmail.setFocus(true);
		fromEmail.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Email Sending Result");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending email via our server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		class MyHandler implements ClickHandler, KeyUpHandler {
			@Override
			public void onClick(ClickEvent event) {
				sendEmailToServer();
			}

			@Override
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendEmailToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendEmailToServer() {
				EmailContent email = new EmailContent(fromEmail.getText(),
						Arrays.asList(toEmails.getText().split(",")),
						subject.getText(),
						content.getText());
				mailSendingService.sendEmail(email,
						new AsyncCallback<ServerResponse>() {
							@Override
							public void onFailure(Throwable caught) {
								dialogBox.setText("Failed to send email");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							@Override
							public void onSuccess(ServerResponse result) {
								dialogBox.setText("Result: "
										+ result.getMessage());
								if (result.isSuccess()) {
									dialogBox.setText("Result: "
											+ result.getMessage());
									serverResponseLabel
											.removeStyleName("serverResponseLabelError");
								} else {
									dialogBox.setText("Failure: "
											+ result.getMessage());
								}
								serverResponseLabel.setHTML("Details: "
										+ result.getMessage());
								dialogBox.center();
								closeButton.setFocus(true);
							}
						});
			}
		}

		// Install a handler
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
	}
}
